var router   = require('express').Router();
var wx       = require('../components/backend/service').weixin;
var Promise  = require('promise');
var https    = require('https');
module.exports = function () {
  router.get('/', function (req, res) {
    console.log("****ip address****", req.connection.remoteAddress);
    console.log("****signature****", req.query.signature);
    console.log("****echostr****", req.query.echostr);
    console.log("****timestamp****", req.query.timestamp);
    console.log("****nonce****", req.query.nonce);

    var data = {
      "ip"       : req.connection.remoteAddress,
      "token"    : "weixin",
      "signature": req.query.signature,
      "echostr"  : req.query.echostr,
      "timestamp": req.query.timestamp,
      "nonce"    : req.query.nonce
    };

    res.send(req.query.echostr);
    //res.render( './weixin/login',data);
  });

  router.post('/', function (req, res) {
    var reqData = {
      "token"    : "weixin",
      "signature": req.query.signature,
      "echostr"  : req.query.echostr,
      "timestamp": req.query.timestamp,
      "nonce"    : req.query.nonce
    };

    var formData = "";

    /**
     * valid send message legel
     * @returns {*|exports|module.exports}
     */
    var isLegel = function () {
      return new Promise(function (resolve, reject) {
        var flag = wx.isLegel(reqData.signature, reqData.timestamp, reqData.nonce, reqData.token);
        if (!flag) {
          // reject();
          console.log("the message is unlegel");
        }
        resolve();
      });
    };

    /**
     * 1.analysis request message;
     * 2.send response message;
     * 3.get user id;
     * @returns userID
     */
    var getReqMsg = function () {
      return wx.processMessage(formData, res);
    };

    // 接收微信消息
    req.on("data", function (data) {
      formData += data;
    });

    // 根据接收的消息进行处理
    req.on("end", function () {
      isLegel().then(getReqMsg).then(function (data) {
        console.log('>>>>>> [Allspark].[INFO].' + data.action_type + ' successed!');
        console.log('>>>>>> [Allspark].[INFO].MSG : ' + data.msg);
        res.writeHead(200, {
          'Content-Type': 'text/xml'
        });
        res.end(data.msg);
      }).catch(function (err) {
        console.log(err);
      });
    });
  });
  return router;
};